import { toast } from 'sard-uniapp'
import { reactive, ref } from 'vue'
import { authModule } from '@/store/modules/authModule'
import { tabbarList } from '@/tabbar/config'
import { isPageTabbar } from '@/tabbar/store'
import { ensureDecodeURIComponent } from '@/utils'

// 登录类型枚举
export enum LoginType {
  WECHAT = 'wechat',
  ACCOUNT = 'account',
  PHONE = 'phone',
}

// 表单数据接口
export interface LoginFormData {
  username: string
  password: string
  phone: string
  verifyCode: string
  agreeTerms: boolean
}

// 验证码倒计时 composable
export function useVerifyCode() {
  const countdown = ref(0)
  const countdownTimer = ref<NodeJS.Timeout | null>(null)

  const startCountdown = () => {
    countdown.value = 60
    countdownTimer.value = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer.value!)
        countdownTimer.value = null
      }
    }, 1000)
  }

  const sendVerifyCode = async (phone: string) => {
    if (!phone) {
      toast.fail('请输入手机号')
      return
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      toast.fail('请输入正确的手机号')
      return
    }

    if (countdown.value > 0) {
      return
    }

    try {
      // TODO: 调用发送验证码 API
      console.log('发送验证码到:', phone)
      toast.success('验证码已发送')
      startCountdown()
    }
    catch (error) {
      console.error('发送验证码失败:', error)
      toast.fail('发送验证码失败')
    }
  }

  const clearCountdown = () => {
    if (countdownTimer.value) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
    }
    countdown.value = 0
  }

  return {
    countdown,
    sendVerifyCode,
    clearCountdown,
  }
}

// 登录表单 composable
export function useLoginForm() {
  const formData = reactive<LoginFormData>({
    username: '',
    password: '',
    phone: '',
    verifyCode: '',
    agreeTerms: false,
  })

  const resetForm = () => {
    formData.username = ''
    formData.password = ''
    formData.phone = ''
    formData.verifyCode = ''
    formData.agreeTerms = false
  }

  const validateForm = (type: LoginType): boolean => {
    if (!formData.agreeTerms) {
      toast.fail('请同意用户协议和隐私政策')
      return false
    }

    switch (type) {
      case LoginType.ACCOUNT:
        if (!formData.username) {
          toast.fail('请输入用户名')
          return false
        }
        if (!formData.password) {
          toast.fail('请输入密码')
          return false
        }
        break
      case LoginType.PHONE:
        if (!formData.phone) {
          toast.fail('请输入手机号')
          return false
        }
        if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
          toast.fail('请输入正确的手机号')
          return false
        }
        if (!formData.verifyCode) {
          toast.fail('请输入验证码')
          return false
        }
        break
    }

    return true
  }

  return {
    formData,
    resetForm,
    validateForm,
  }
}

// 登录处理 composable
export function useLoginHandler() {
  const { wxLogin } = authModule()

  const handleLoginSuccess = (redirectUrl?: string) => {
    toast.success('登录成功')
    setTimeout(() => {
      const url = redirectUrl || tabbarList[0].pagePath
      if (isPageTabbar(url)) {
        uni.switchTab({ url })
      }
      else {
        uni.navigateTo({ url })
      }
    }, 1500)
  }

  const doWechatLogin = async (redirectUrl?: string) => {
    try {
      await wxLogin()
      handleLoginSuccess(redirectUrl)
    }
    catch (error: any) {
      console.error('微信登录失败:', error)
      toast.fail(error.message || '登录失败')
    }
  }

  const doAccountLogin = async (username: string, password: string, redirectUrl?: string) => {
    try {
      // TODO: 调用账号密码登录 API
      console.log('账号密码登录:', { username, password })

      // 模拟登录请求
      await new Promise(resolve => setTimeout(resolve, 1000))

      handleLoginSuccess(redirectUrl)
    }
    catch (error: any) {
      console.error('账号密码登录失败:', error)
      toast.fail(error.message || '登录失败')
    }
  }

  const doPhoneLogin = async (phone: string, verifyCode: string, redirectUrl?: string) => {
    try {
      // TODO: 调用手机号验证码登录 API
      console.log('手机号登录:', { phone, verifyCode })

      // 模拟登录请求
      await new Promise(resolve => setTimeout(resolve, 1000))

      handleLoginSuccess(redirectUrl)
    }
    catch (error: any) {
      console.error('手机号登录失败:', error)
      toast.fail(error.message || '登录失败')
    }
  }

  const doThirdPartyLogin = async (platform: 'gitee' | 'github', redirectUrl?: string) => {
    try {
      // TODO: 调用第三方登录 API
      console.log(`${platform} 登录`)

      // 模拟登录请求
      await new Promise(resolve => setTimeout(resolve, 1000))

      handleLoginSuccess(redirectUrl)
    }
    catch (error: any) {
      console.error(`${platform} 登录失败:`, error)
      toast.fail(error.message || '登录失败')
    }
  }

  return {
    doWechatLogin,
    doAccountLogin,
    doPhoneLogin,
    doThirdPartyLogin,
  }
}
